//
// Created by jiaxv on 2025/10/5.
//
#include "ldacs_corenet.h"
#include <ld_net.h>
#include <ld_dashboard.h>
#include "services/dashboard.h"

#include "as_entity.h"
#include "elements.h"
#include "util/log.h"

l_err dashboard_data_recv(basic_conn_t *bc) {
    if (!bc->read_pkt) {
        log_warn("Read pkt is null");
        return LD_ERR_NULL;
    }

    dashboard_data_t to_resp;

    cJSON *root = cJSON_Parse((const char *)bc->read_pkt->ptr);
    unmarshel_json(root, &to_resp, &dashboard_data_tmpl_desc);
    cJSON_Delete(root);

    switch (to_resp.type) {
        case DASHBOARD_GET_CN_DATA: {
            dashboard_get_cn_data_t get_cn_data;
            cJSON *data = cJSON_Parse(to_resp.data);
            unmarshel_json(data, &get_cn_data, dashboard_func_defines[DASHBOARD_GET_CN_DATA].tmpl);
            cJSON_Delete(data);

            net_element_t *net_element = get_element_by_SAC(get_cn_data.SAC);
            if (!net_element) {
                log_warn("No valid element");
                return LD_ERR_NULL;
            }

            dashboard_set_cn_data_t set_data = {0};
            if (generate_as_info_json(net_element, &set_data) != LD_OK) {
                cn_log_warn(net_element->element_tag, INTERFACE_UNDEFINED, "Generate JSON failed");
                return LD_ERR_NULL;
            }

            handle_set_cn_data_dashboard(&net_element->dashboard_obj, &set_data);

            // free_set_cn_data(&set_data);

            break;
        }
        default: {
            log_warn("Wrong Response Type");
            return LD_ERR_INTERNAL;
        }
    }

    return LD_OK;
}

void handle_register_cn_dashboard(dashboard_obj_t *obj, element_type_t type, uint16_t SAC) {
    dashboard_data_send(obj, CN_REGISTER,
                        &(dashboard_register_cn_t){.type = type, .element = SAC});
}

void handle_upload_cn_signalling_dashboard(dashboard_obj_t *obj, uint16_t sender, uint16_t receiver, uint8_t interface, uint8_t signalling) {
    dashboard_data_send(obj, CN_SIGNALLING,
                        &(dashboard_upload_cn_signalling_t){.sender = sender, .receiver = receiver, .interface = interface, .signalling = signalling});
}

void handle_set_cn_data_dashboard(dashboard_obj_t *obj, dashboard_set_cn_data_t *set) {
    dashboard_data_send(obj, CN_SET_CN_DATA, set);
}

// void handle_upload_cn_signalling_dashboard(dashboard_obj_t *obj, element_type_t type, buffer_t *to_send) {
//     buffer_t *element_buffer = init_buffer_unptr();
//     CLONE_TO_CHUNK(*element_buffer, (uint8_t*)element_tag, strlen(element_tag));
//
//     dashboard_data_send(obj, CN_SIGNALLING,
//                         &(dashboard_register_cn_t){.type = type, .element = element_buffer});
//     free_buffer(element_buffer);
// }

l_err init_dashboard_service() {
    log_info("The ldacs corenet is using 'DASHBOARD' mode. Connecting to %s:%d.", BACKEND_IP"\0", BACKEND_PORT);
    // init_dashboard(&dashboard_obj, dashboard_data_recv);

    return LD_OK;
}
